<template>
  <component v-if="domainList.length" :is="loginInstance" :domainList="domainList" />
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, defineAsyncComponent } from 'vue';
  import type { DropMenu } from '/@/components/Dropdown';
  import { useRouter } from 'vue-router';
  import { useDomain } from '/@/locales/useDomain';
  import { getTenantList } from '/@/api/sys/user';
  import { getLoginDirs } from './helper';

  let loginInstance;
  const { currentRoute } = useRouter();

  const domainList = ref<DropMenu[]>([]);
  const loginFile = getLoginDirs();

  async function init() {
    const { setProjectInfo, changeDomain, changeTenantId, getDomain, getTenantId } = useDomain();
    let domain = unref(getDomain);
    setProjectInfo({ domain });
    const { query } = unref(currentRoute);

    if (query.domain) {
      domain = query.domain as string;
      changeDomain(domain);
      setProjectInfo({ domain });
    }

    const ret = await getTenantList(domain);
    let newDomain = domain;
    if (!domain) {
      newDomain = ret[0]?.domain;
      changeDomain(newDomain);
      setProjectInfo({ domain });
    }
    await getLoginComponent(newDomain);

    setProjectInfo({
      title: ret[0].config.title,
      icon: ret[0].config.icon.url,
      logo: ret[0].config.logo.url,
    });

    console.log('ret', ret);

    if (ret.length <= 1) {
      changeTenantId(ret[0].id);
    } else {
      !unref(getTenantId) && changeTenantId(ret[0].id);
    }
    ret.forEach((el) => {
      el.text = el.name;
      el.event = el.id;
    });

    domainList.value = ret;
  }

  async function getLoginComponent(domain) {
    let tenant = 'hlxb';

    console.log('domain2', domain, loginFile);

    if (domain) {
      const loginArr = loginFile;

      if (loginArr.includes(domain)) {
        tenant = domain;
      } else {
        tenant = 'init';
      }
    }

    console.log('tenant', tenant);

    const login = defineAsyncComponent(() => import(`./${tenant}/Login.vue`));
    loginInstance = login;
  }

  onMounted(async () => {
    await init();
  });
</script>
